/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se.sll.service.catalogue.composite.camel.processor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.Exchange;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import se.sll.service.catalogue.capacity.api.model.CareUnitRefList;
import se.sll.service.catalogue.capacity.api.model.Unit;
import se.sll.service.catalogue.capacity.api.model.UnitList;

/**
 *
 * @author khaleddaham
 */
@Slf4j
public class CapacityProcessor {

    ObjectMapper mapper = new ObjectMapper();

    /**
     * UnmarshalL JSON to CapacityResponse list
     *
     * @param exchange CareUnitRefList
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    public void capacityResponseJSON(Exchange exchange) throws JsonParseException, JsonMappingException, IOException {
        List<CareUnitRefList> capacities = mapper.readValue(exchange.getIn().getBody(String.class), new TypeReference<List<CareUnitRefList>>() {
        });
        /**
        for (CareUnitRefList cr : capacities) {
            for (Product p : cr.getProduct()) {
                for (Capacity c : p.getCapacity()) {
                    String date = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(c.getValidTo());
                    c.setValidTo(date);
                }
            }
        }
        */
        exchange.getIn().setBody(capacities);
    }

    /**
     * Convert a string list to UnitList for marshalling to JSON.
     *
     * @param exchange
     */
    @SuppressWarnings("unchecked")
    public void listToCapacityModel(Exchange exchange) {
        UnitList l = new UnitList();
        List<Unit> lu = new ArrayList<>();
        List<String> hsaIdList = (List<String>) exchange.getIn().getBody();
        for (String a : hsaIdList) {
            Unit u = new Unit();
            u.setUnitId(a);
            lu.add(u);
        }
        l.setUnits(lu);
        exchange.getIn().setBody(l);
    }
}
